//
//  WNSuspendTool.swift
//  WalkNovel
//
//  Created by Kevin on 6/3/2023.
//

import UIKit

let radious: CGFloat = 60.0

class WNSuspendTool: NSObject {
    
    static let shared = WNSuspendTool()
    
    var suspendW: SuspendWindow?
    
    var bookModel: BookDetailModel?
    
    var readVC: WNReadVC?

    var audioVC: WNAudioVC?
    
    var audioModel: MusicModel?
            
    var origin: CGPoint = CGPoint(x: ScreenW-radious-6, y: ScreenH-TabBarTotalHeight-radious-6)

    static func showSuspendWindow(_ type: Int, _ rootVC: WNBaseVC, _ readModel: BookDetailModel?, _ audioModel: MusicModel?) {
        let tool = WNSuspendTool.shared
        UIView.animate(withDuration: 0.25, delay: 0, options: [.curveLinear], animations: {
            tool.suspendW = nil
            tool.bookModel = nil
            tool.readVC = nil
            tool.audioModel = nil
            tool.audioVC = nil
        }) { (finish) in
            if finish {
                if type == 0 {
                    tool.suspendW = SuspendWindow.init(read: rootVC as! WNReadVC, CGRect(origin: WNSuspendTool.shared.origin, size: .init(width: radious, height: radious)), readModel)
                    tool.suspendW?.showRead()
                    tool.bookModel = readModel
                    tool.readVC = rootVC as? WNReadVC
                }else if type == 1 {
                    tool.suspendW = SuspendWindow.init(audio: rootVC as! WNAudioVC, CGRect(origin: WNSuspendTool.shared.origin, size: .init(width: radious, height: radious)), audioModel)
                    tool.suspendW?.showAudio()
                    tool.audioModel = audioModel
                    tool.audioVC = rootVC as? WNAudioVC
                }
            }
        }
    }
    
    static func remove(_ suspendWindow: SuspendWindow) {
        UIView.animate(withDuration: 0.25, delay: 0, options: [.curveLinear], animations: {
            suspendWindow.alpha = 0
        }) { (finish) in
            if finish {
                WNSuspendTool.shared.suspendW = nil
                WNSuspendTool.shared.readVC = nil
                WNSuspendTool.shared.bookModel = nil
                WNSuspendTool.shared.audioVC = nil
                WNSuspendTool.shared.audioModel = nil
            }
        }
    }
    
    static func setLatestOrigin(origin: CGPoint) {
        WNSuspendTool.shared.origin = origin
    }
}

class SuspendWindow: UIWindow {
    
    lazy var bookImage: UIImageView = {
        let imageView = UIImageView(frame: bounds)
        imageView.contentMode = .scaleAspectFill
        imageView.isUserInteractionEnabled = true
        imageView.wn_cornerCustom([.allCorners], 30)
        return imageView
    }()
    
    lazy var playBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.frame = .init(x: -5, y: 32, width: 36, height: 36)
        btn.setImage(UIImage(named: "music_play_s"), for: .normal)
        btn.setImage(UIImage(named: "music_pause_s"), for: .selected)
        btn.rx.tap.bind { [weak self] in
            self?.audioVC?.pauseOrPlay()
            btn.isSelected = !btn.isSelected
        }.disposed(by: rx.disposeBag)
        return btn
    }()
    
    lazy var closeBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.frame = CGRect(x: 36, y: -4, width: 28, height: 28)
        btn.setImage(UIImage(named: "lbrary_close"), for: .normal)
        btn.rx.tap.bind { [weak self] in
            self?.closeSuspendView()
        }.disposed(by: rx.disposeBag)
        return btn
    }()
    
    var spaceW: CGFloat = 6.0
        
    var readVC: WNReadVC?
    
    var audioVC: WNAudioVC?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        sizeToFit()
    }

    convenience init(read: WNReadVC, _ frame: CGRect, _ model: BookDetailModel?) {
        self.init(frame: frame)
        readVC = read
        bookImage.wn_setupImg(model?.coverUrl, placeHolder: "placeholder_book_square")
    }
    
    func showRead() {
        windowLevel = UIWindow.Level.alert - 1
        isHidden = false
        addSubview(bookImage)
        addSubview(closeBtn)
        let panGesture = UIPanGestureRecognizer.init(target: self, action: #selector(didPan(_:)))
        addGestureRecognizer(panGesture)
        let tapGesture = UITapGestureRecognizer.init(target: self, action: #selector(didTap))
        addGestureRecognizer(tapGesture)
    }
    
    convenience init(audio: WNAudioVC, _ frame: CGRect, _ model: MusicModel?) {
        self.init(frame: frame)
        audioVC = audio
        playBtn.isHidden = false
        playBtn.isSelected = audioVC?.playState == .playing
        bookImage.wn_setupImg(model?.cover, placeHolder: "placeholder_book_square")
    }
    
    func showAudio() {
        windowLevel = UIWindow.Level.alert - 1
        isHidden = false
        addSubview(bookImage)
        addSubview(playBtn)
        addSubview(closeBtn)
        let panGesture = UIPanGestureRecognizer.init(target: self, action: #selector(didPan(_:)))
        addGestureRecognizer(panGesture)
        let tapGesture = UITapGestureRecognizer.init(target: self, action: #selector(didTap))
        addGestureRecognizer(tapGesture)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // 关闭
    func closeSuspendView() {
        WNSuspendTool.shared.readVC?.stopReadTimer()
        WNSuspendTool.shared.audioVC?.reset()
        WNSuspendTool.remove(self)
    }
    
    @objc func didTap() {
        readVC?.wn_showFullView()
        audioVC?.wn_showFullView()
        WNSuspendTool.remove(self)
    }
    
    @objc func didPan(_ panGesture: UIPanGestureRecognizer) {
        let point = panGesture.translation(in: panGesture.view)
        var originX = frame.origin.x + point.x
        if originX < spaceW {
            originX = spaceW
        } else if originX > UIScreen.main.bounds.width - radious - spaceW {
            originX = UIScreen.main.bounds.width - radious - spaceW
        }
        var originY = frame.origin.y + point.y
        if originY < NaviTotalHeight {
            originY = NaviTotalHeight
        } else if originY > UIScreen.main.bounds.height - radious - TabBarTotalHeight {
            originY = UIScreen.main.bounds.height - radious - TabBarTotalHeight
        }
        frame = CGRect.init(x: originX, y: originY, width: bounds.width, height: bounds.height)
        if panGesture.state == UIGestureRecognizer.State.cancelled || panGesture.state == UIGestureRecognizer.State.ended || panGesture.state == UIGestureRecognizer.State.failed {
            adjustFrameAfterPan()
        }
        panGesture.setTranslation(CGPoint.zero, in: self)
    }
    
    fileprivate func adjustFrameAfterPan() {
        var originX: CGFloat = spaceW
        if center.x < UIScreen.main.bounds.width / 2 {
            originX = spaceW
        } else if center.x >= UIScreen.main.bounds.width / 2 {
            originX = UIScreen.main.bounds.width-radious-spaceW
        }
        UIView.animate(withDuration: 0.25, animations: {
            self.frame = CGRect.init(x: originX, y: self.frame.origin.y, width: self.frame.size.width, height: self.frame.size.height)
        }) { (complete) in
            WNSuspendTool.setLatestOrigin(origin: self.frame.origin)
        }
    }
}

func closeSuspendView() {
    if WNSuspendTool.shared.suspendW != nil {
        WNSuspendTool.shared.suspendW?.closeSuspendView()
    }
}
